<template>
  <div id="replace">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 上 -->
      <div slot="header" class="clearfix">
        <div style="margin-top: 15px">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            v-model="search"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchFn()"
            ></el-button>
          </el-input>
          <!-- 添加按钮 -->
          <el-button type="primary" @click="dialogFormVisible = true"
            >添加用户</el-button
          >
        </div>
      </div>
      <!-- 表格数据 -->
      <el-table
        ref="singleTable"
        :data="tableData"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column property="username" label="姓名"></el-table-column>
        <el-table-column property="email" label="邮箱"></el-table-column>
        <el-table-column property="mobile" label="电话"></el-table-column>
        <el-table-column property="role_name" label="角色"></el-table-column>
        <el-table-column property="mg_state" label="状态">
          <template slot-scope="state">
            <el-switch
              v-model="state.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(state.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="handleEdit(scope.$index, scope.row)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDelete(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 添加用户模态框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="form1">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              min: 3,
              max: 6,
              message: '长度在 3 到 6 个字符',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model="form1.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              min: 6,
              max: 10,
              message: '长度在 6 到 10个字符',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model="form1.password"></el-input>
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="form1.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="电话"
          :rules="[
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            {
              min: 11,
              max: 11,
              message: '请输入正确的电话号码',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="form1.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改用户模态框-->
    <el-dialog title="修改" :visible.sync="editdialogFormVisible">
      <el-form :model="form">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            {
              min: 3,
              max: 6,
              message: '长度在 3 到 6 个字符',
              trigger: 'blur',
            },
          ]"
        >
          <el-input v-model="form.username" disabled></el-input>
        </el-form-item>
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            {
              type: 'email',
              message: '请输入正确的邮箱地址',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="电话"
          :rules="[
            { required: true, message: '请输入电话号码', trigger: 'blur' },
            {
              min: 11,
              max: 11,
              message: '请输入正确的电话号码',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editadd()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  props: [],
  data() {
    return {
      // 搜索
      search: "",
      // 数组
      tableData: [],
      currentRow: null,
      dialogFormVisible: false,
      editdialogFormVisible: false,
      // 定义一个form对象 接收表单内容
      form1: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      formLabelWidth: "120px",
      currentPage: 1, //分页数据
      total: 1, //数据总量
      pagesize: 5, //每页绑定几条数据
      pagenum: 1, //显示第几页
    };
  },
  methods: {
    //   渲染页面
    show() {
      // 拿取在线文档的用户数据列表添加到数组里
      this.$http
        .get("/users", {
          // params方式请求参数
          params: {
            query: "", //查询参数为空
            pagenum: this.pagenum, //当前页码         为自己定义的显示第几页
            pagesize: this.pagesize, //每页显示条数    为自己定义的每页绑定几条数据
          },
        })
        .then((res) => {
          console.log(res);
          // 把响应参数的总记录数放在       自己定义的数据总量
          this.total = res.data.data.total;
          //把响应参数的用户数据集合放在    自己定义的数组里
          this.tableData = res.data.data.users;
        });
    },
    // 点击修改按钮事件
    handleEdit(index, row) {
      console.log(index, row);
      // 点击修改是 模态框为true显示页面
      this.editdialogFormVisible = true;
      // 把当前这行的id存到本地
      localStorage.setItem("id", row.id);
      // 拿取线在文档的修改用户状态的数据
      this.$http.get("/users/" + row.id).then((res) => {
        console.log(res);
        //把响应数据放在    自己定义的from对象里面对应的内容
        this.form.username = res.data.data.username;
        this.form.email = res.data.data.email;
        this.form.mobile = res.data.data.mobile;
      });
    },
     // 点击删除按钮事件
      handleDelete(row) {
         console.log(row);
      this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           this.$http.delete("users/" + row.id).then(res=>{
             if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg);
          }
          this.show();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
           });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 点击添加按钮事件
    add() {
      // 拿取在线文档的添加用户  请求的参数是输入的参数时
      this.$http
        .post("/users", {
          username: this.form1.username,
          password: this.form1.password,
          email: this.form1.email,
          mobile: this.form1.mobile,
        })
        .then((res) => {
          console.log(res);
          // 返回状态为201时添加成功从新喧染页面
          if (res.data.meta.status == 201) {
            this.show();
            this.form1.username = "";
            this.form1.password = "";
            this.form1.email = "";
            this.form1.mobile = "";
          }
        });
      // 点击修改中的确定 模态框为false关闭页面
      this.dialogFormVisible = false;
    },
    // 点击修改中确认按钮事件
    editadd() {
      // 定义一个值 来接收本地存储的id
      let id = localStorage.getItem("id");
      // 拿取在线文档的编辑用户提交   请求的参数是修改时输入的参数
      this.$http
        .put("/users/" + id, {
          id: id,
          email: this.form.email,
          mobile: this.form.mobile,
        })
        .then((res) => {
          let xg = confirm("您确定要修改吗？");
          // 判断确认或取消
          if (xg) {
            // 判断状态为200是修改成功
            if (res.data.meta.status == 200) {
              // 关闭模态框
              this.editdialogFormVisible = false;
              // 显示页面
              this.show();
            }
          } else {
            //关闭模态框
            this.editdialogFormVisible = false;
          }
        });
    },
    //每页几条
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      this.show();
    },
    // 当前第几页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagenum = val;
      this.show();
    },
    // 点击搜索按钮事件
    searchFn() {
      // 把数组里面你输入的内容过滤出来，从新放到这个数组
      this.tableData = this.tableData.filter((item) => {
        // includes是es6字符串查找的方法
        return item.username.includes(this.search);
      });
      // 判断输入框为空时，渲染页面
      if (this.search == "") {
        this.show();
      }
    },
    // 修改状态
    userStateChanged(row) {
      //发送请求进行状态修改
      this.$http.put(`users/${row.id}/state/${row.mg_state}`).then((res) => {
        console.log(res);
        //如果返回状态为异常状态则报错并返回
        if (res.data.meta.status !== 200) {
          row.mg_state != row.mg_state;
          return this.$message.error("修改状态失败");
        }
        this.$message.success("更新状态成功");
      });
    },
  },
  computed: {},
  watch: {},
  created() {
    this.show();
  },
  mounted() {},
};
</script>


<style scoped>
.el-input {
  width: 500px;
  margin-right: 50px;
}
.box-card {
  margin-top: 20px;
}
</style>